<template>
  <div class="settings-page">
    <div class="settings-header">
      <h1>系统设置</h1>
      <p>配置您的聊天界面偏好设置</p>
    </div>

    <div class="settings-content">
      <div class="settings-section">
        <h2 class="section-title">外观设置</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">主题模式</label>
            <span class="setting-description">选择界面的颜色主题</span>
          </div>
          <div class="setting-control">
            <select v-model="settings.theme" @change="updateTheme">
              <option value="light">浅色主题</option>
              <option value="dark">深色主题</option>
              <option value="auto">跟随系统</option>
            </select>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">界面密度</label>
            <span class="setting-description">调整界面元素的紧凑程度</span>
          </div>
          <div class="setting-control">
            <select v-model="settings.density" @change="updateDensity">
              <option value="compact">紧凑</option>
              <option value="normal">正常</option>
              <option value="comfortable">舒适</option>
            </select>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">语言设置</label>
            <span class="setting-description">选择界面显示语言</span>
          </div>
          <div class="setting-control">
            <select v-model="settings.language" @change="updateLanguage">
              <option value="zh-CN">简体中文</option>
              <option value="zh-TW">繁體中文</option>
              <option value="en-US">English</option>
              <option value="ja-JP">日本語</option>
            </select>
          </div>
        </div>
      </div>

      <div class="settings-section">
        <h2 class="section-title">布局设置</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">侧边栏默认状态</label>
            <span class="setting-description">设置侧边栏的默认显示状态</span>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input 
                type="checkbox" 
                v-model="settings.sidebarCollapsed"
                @change="updateSidebarState"
              />
              <span class="slider"></span>
            </label>
            <span class="switch-label">{{ settings.sidebarCollapsed ? '折叠' : '展开' }}</span>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">客户信息栏</label>
            <span class="setting-description">控制客户信息栏的显示</span>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input 
                type="checkbox" 
                v-model="settings.clientInfoVisible"
                @change="updateClientInfoState"
              />
              <span class="slider"></span>
            </label>
            <span class="switch-label">{{ settings.clientInfoVisible ? '显示' : '隐藏' }}</span>
          </div>
        </div>
      </div>

      <div class="settings-section">
        <h2 class="section-title">通知设置</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">桌面通知</label>
            <span class="setting-description">允许显示桌面通知</span>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input 
                type="checkbox" 
                v-model="settings.notifications"
                @change="updateNotifications"
              />
              <span class="slider"></span>
            </label>
            <span class="switch-label">{{ settings.notifications ? '开启' : '关闭' }}</span>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">声音提醒</label>
            <span class="setting-description">新消息时播放提示音</span>
          </div>
          <div class="setting-control">
            <label class="switch">
              <input 
                type="checkbox" 
                v-model="settings.soundEnabled"
                @change="updateSound"
              />
              <span class="slider"></span>
            </label>
            <span class="switch-label">{{ settings.soundEnabled ? '开启' : '关闭' }}</span>
          </div>
        </div>
      </div>

      <div class="settings-section">
        <h2 class="section-title">高级设置</h2>
        
        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">布局配置</label>
            <span class="setting-description">管理布局配置文件</span>
          </div>
          <div class="setting-control">
            <div class="button-group">
              <button @click="exportLayout" class="btn btn-secondary">
                <i class="icon-export"></i>
                <span>导出配置</span>
              </button>
              <button @click="importLayout" class="btn btn-secondary">
                <i class="icon-import"></i>
                <span>导入配置</span>
              </button>
              <button @click="resetLayout" class="btn btn-danger">
                <i class="icon-reset"></i>
                <span>重置布局</span>
              </button>
            </div>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <label class="setting-label">清除数据</label>
            <span class="setting-description">清除本地存储的数据</span>
          </div>
          <div class="setting-control">
            <button @click="clearData" class="btn btn-danger">
              <i class="icon-trash"></i>
              <span>清除所有数据</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="settings-footer">
      <div class="footer-info">
        <p>设置会自动保存到本地存储</p>
        <p class="version-info">版本: 1.0.0</p>
      </div>
    </div>

    <!-- 文件输入（隐藏） -->
    <input 
      ref="fileInput" 
      type="file" 
      accept=".json"
      @change="handleFileImport"
      style="display: none"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUIStore } from '@/stores/ui'
import { useLayoutPersistence } from '@/composables/useLayoutPersistence'

const uiStore = useUIStore()
const { exportLayout: exportLayoutConfig, importLayout: importLayoutConfig, resetLayout: resetLayoutConfig } = useLayoutPersistence()

const fileInput = ref<HTMLInputElement>()

// 设置状态
const settings = reactive({
  theme: 'light',
  density: 'normal',
  language: 'zh-CN',
  sidebarCollapsed: false,
  clientInfoVisible: true,
  notifications: true,
  soundEnabled: true
})

// 方法
const updateTheme = () => {
  uiStore.setTheme(settings.theme as any)
}

const updateDensity = () => {
  // uiStore.setDensity(settings.density as any)
  console.log('密度更新:', settings.density)
}

const updateLanguage = () => {
  uiStore.setLanguage(settings.language)
}

const updateSidebarState = () => {
  uiStore.setSidebarCollapsed(settings.sidebarCollapsed)
}

const updateClientInfoState = () => {
  uiStore.setClientInfoVisible(settings.clientInfoVisible)
}

const updateNotifications = () => {
  uiStore.setNotifications(settings.notifications)
}

const updateSound = () => {
  uiStore.setSoundEnabled(settings.soundEnabled)
}

const exportLayout = () => {
  try {
    const config = exportLayoutConfig()
    const blob = new Blob([config], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'chat-layout-config.json'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    
    // 显示成功消息
    uiStore.addNotification({
      type: 'success',
      title: '导出成功',
      message: '布局配置已导出到文件'
    })
  } catch (error) {
    uiStore.addNotification({
      type: 'error',
      title: '导出失败',
      message: '无法导出布局配置'
    })
  }
}

const importLayout = () => {
  fileInput.value?.click()
}

const handleFileImport = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const config = e.target?.result as string
      const success = importLayoutConfig(config)
      
      if (success) {
        uiStore.addNotification({
          type: 'success',
          title: '导入成功',
          message: '布局配置已应用'
        })
        // 刷新设置显示
        loadSettings()
      } else {
        throw new Error('Invalid config format')
      }
    } catch (error) {
      uiStore.addNotification({
        type: 'error',
        title: '导入失败',
        message: '配置文件格式不正确'
      })
    }
  }
  reader.readAsText(file)
}

const resetLayout = () => {
  if (confirm('确定要重置所有布局设置吗？此操作不可撤销。')) {
    resetLayoutConfig()
    loadSettings()
    
    uiStore.addNotification({
      type: 'success',
      title: '重置成功',
      message: '布局已重置为默认设置'
    })
  }
}

const clearData = () => {
  if (confirm('确定要清除所有本地数据吗？此操作不可撤销。')) {
    localStorage.clear()
    sessionStorage.clear()
    
    uiStore.addNotification({
      type: 'success',
      title: '清除成功',
      message: '所有本地数据已清除，页面将刷新'
    })
    
    setTimeout(() => {
      window.location.reload()
    }, 2000)
  }
}

const loadSettings = () => {
  settings.theme = uiStore.theme
  settings.sidebarCollapsed = uiStore.sidebarCollapsed
  settings.clientInfoVisible = uiStore.clientInfoVisible
  settings.notifications = uiStore.notifications
  settings.soundEnabled = uiStore.soundEnabled
  settings.language = uiStore.language
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.settings-page {
  max-width: 800px;
  margin: 0 auto;
  padding: var(--spacing-xl);
}

.settings-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.settings-header h1 {
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-2xl);
  color: var(--color-text);
}

.settings-header p {
  color: var(--color-text-secondary);
  font-size: var(--font-size-lg);
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.settings-section {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-xl);
}

.section-title {
  margin-bottom: var(--spacing-lg);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text);
  padding-bottom: var(--spacing-md);
  border-bottom: 1px solid var(--color-border);
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg) 0;
  border-bottom: 1px solid var(--color-border-light);
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info {
  flex: 1;
}

.setting-label {
  display: block;
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  color: var(--color-text);
  margin-bottom: var(--spacing-xs);
}

.setting-description {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.setting-control {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

select {
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-md);
  background: var(--color-background);
  color: var(--color-text);
  font-size: var(--font-size-sm);
  min-width: 120px;
}

/* 开关样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--color-border);
  transition: var(--transition-fast);
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: var(--transition-fast);
  border-radius: 50%;
}

input:checked + .slider {
  background-color: var(--color-primary);
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.switch-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  min-width: 40px;
}

/* 按钮组 */
.button-group {
  display: flex;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid transparent;
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  text-decoration: none;
}

.btn-secondary {
  background: var(--color-surface);
  color: var(--color-text);
  border-color: var(--color-border);
}

.btn-secondary:hover {
  background: var(--color-hover);
  border-color: var(--color-border-dark);
}

.btn-danger {
  background: var(--color-error);
  color: var(--color-text-inverse);
  border-color: var(--color-error);
}

.btn-danger:hover {
  background: var(--color-error-dark);
  border-color: var(--color-error-dark);
}

.settings-footer {
  margin-top: var(--spacing-xl);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--color-border);
  text-align: center;
}

.footer-info p {
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.version-info {
  font-weight: var(--font-weight-medium);
}

/* 图标样式 */
.icon-export::before { content: '📤'; }
.icon-import::before { content: '📥'; }
.icon-reset::before { content: '🔄'; }
.icon-trash::before { content: '🗑️'; }

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-page {
    padding: var(--spacing-lg);
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }
  
  .setting-control {
    width: 100%;
    justify-content: flex-end;
  }
  
  .button-group {
    width: 100%;
    justify-content: center;
  }
  
  .btn {
    flex: 1;
    justify-content: center;
  }
}
</style>